package com.znyj.cloud.device.pack;

import com.alibaba.fastjson.JSONObject;
import com.znyj.cloud.chain.util.ByteUtil;
import com.znyj.cloud.chain.util.CheckUtil;
import com.znyj.cloud.device.constant.SysConstant;
import com.znyj.cloud.device.entity.TaskEntity;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.zip.CRC32;

/**
 * Created by gaoliwei02 on 17/5/30.
 */

public class TaskSendPackage extends BasePackage {
    private static final Logger logger = Logger.getLogger(TaskSendPackage.class);

    public TaskSendPackage(TaskEntity taskEntity) {
        this.taskEntity = taskEntity;
    }

    public TaskEntity getTaskEntity() {
        return taskEntity;
    }

    private TaskEntity taskEntity;

    public String reportJson() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", taskEntity.getUserId());
        jsonObject.put("deviceId", taskEntity.getDeviceId());
        jsonObject.put("orderId", taskEntity.getOrderId());
        jsonObject.put("durationSec", taskEntity.getDurationSec());
        jsonObject.put("setSendStatus", taskEntity.getSendStatus());
        jsonObject.put("controlMsg", taskEntity.getControlMsg());
        jsonObject.put("userLocation", taskEntity.getUserLocation());
        jsonObject.put("createdTime", taskEntity.getCreateTime());
        jsonObject.put("executeResult", taskEntity.getExecuteResult());
        return jsonObject.toString();
    }

    public TaskSendPackage(Timestamp createTime, String userId, String deviceId, long orderId, long durationSec, int sendStatus, String controlMsg, String userLocation, String executeResult) {
        taskEntity = new TaskEntity();
        taskEntity.setUserId(userId);
        taskEntity.setDeviceId(deviceId);
        taskEntity.setOrderId(orderId);
        taskEntity.setDurationSec(durationSec);
        taskEntity.setSendStatus(sendStatus);
        taskEntity.setControlMsg(controlMsg);
        taskEntity.setUserLocation(userLocation);
        taskEntity.setCreateTime(createTime);
        taskEntity.setExecuteResult(executeResult);
    }

    public void generateAndSendPackage(ChannelHandlerContext ctx) {
        //把data转换成JSON包到字符
        JSONObject jsonObject = new JSONObject();

        if (taskEntity.getControlMsg().equals("up")) {
            jsonObject.put(SysConstant.CTRL_KEY.MSG_TYPE, SysConstant.PACKAGE_VALUE.UP_SENT);
        } else {
            jsonObject.put(SysConstant.CTRL_KEY.MSG_TYPE, SysConstant.PACKAGE_VALUE.CTRL_SENT);
        }
        jsonObject.put(SysConstant.CTRL_KEY.DEVICE_ID, taskEntity.getDeviceId());
        jsonObject.put(SysConstant.CTRL_KEY.ORDER_ID, taskEntity.getOrderId());
        jsonObject.put(SysConstant.CTRL_KEY.ORDER_CREATE_TIME, String.valueOf(taskEntity.getCreateTime().getTime()));
        jsonObject.put(SysConstant.CTRL_KEY.CONTROL_MSG, taskEntity.getControlMsg());
        //试用工厂烧写固件9-7
        //jsonObject.put(SysConstant.CTRL_KEY.ORDER_CREATE_TIME, cdbTaskEntity.getCreateTime());

        byte[] json_byte = new byte[0];
        try {
            json_byte = jsonObject.toString().getBytes("ASCII");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        setPayloadData(json_byte);
        setJsonObject(jsonObject);

        setVersion(SysConstant.HEAD.VERSION_1);
        setFormat(SysConstant.HEAD.FORMAT_JSON);
        setReserved(SysConstant.HEAD.RESERVE);

        CRC32 crc32 = new CRC32();
        crc32.update(getPayloadData());
        int tempCRC = (int) crc32.getValue();
        crc32.reset();

        ByteBuf buf = Unpooled.buffer();
        buf.writeInt(ByteUtil.intTointBIG(SysConstant.HEAD.PROTOCOL_HEAD));
        buf.writeInt(ByteUtil.intTointBIG(tempCRC));
        buf.writeInt(ByteUtil.intTointBIG(getVersion()));
        buf.writeInt(ByteUtil.intTointBIG(getFormat()));
        buf.writeInt(ByteUtil.intTointBIG(getReserved()));
        buf.writeInt(ByteUtil.intTointBIG(getPayloadData().length));
        buf.writeBytes(getPayloadData());
        try {
            //logger.error("ctx:" + ctx.channel().toString() + " len：" + buf);
            ctx.writeAndFlush(buf);
        } catch (Exception e) {
            logger.error(CheckUtil.monitorReport(SysConstant.ERROR_CODE.WRITE_AND_FLUSH, "writeAndFlushError", Long.parseLong(taskEntity.getDeviceId())));

        }
        logger.info("send task to device: {}" + jsonObject.toString());
    }

}
